package net.zjitc.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import net.zjitc.domain.MessageConstant;
import net.zjitc.domain.PageResult;
import net.zjitc.domain.Result;
import net.zjitc.domain.User;
import net.zjitc.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.awt.print.Book;
import java.util.List;

@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping
    public Result add(@RequestBody User user) {
        System.out.println(user);
        try {
            userService.add(user);
        } catch (Exception e) {
            return new Result(false, MessageConstant.ADD_USER_FAIL);
        }
        return new Result(true, MessageConstant.ADD_USER_SUCCESS);
    }

    @DeleteMapping("/{id}")
    public Result deleteById(@PathVariable("id") Integer id) {
        try {
            userService.deleteById(id);
        } catch (Exception e) {
            return new Result(false, MessageConstant.DELETE_USER_FAIL);
        }
        return new Result(true, MessageConstant.DELETE_USER_SUCCESS);
    }

    @GetMapping("/{id}")
    public Result findById(@PathVariable("id") Integer id) {
        User user;
        try {
            user = userService.findById(id);
        } catch (Exception e) {
            return new Result(false, MessageConstant.QUERY_USER_FAIL);
        }
        return new Result(true, MessageConstant.QUERY_USER_SUCCESS, user);
    }

    @PutMapping
    public Result update(@RequestBody User user) {
        try {
            userService.update(user);
        } catch (Exception e) {
            return new Result(false, MessageConstant.EDIT_USER_FAIL);
        }
        return new Result(true, MessageConstant.EDIT_USER_SUCCESS);
    }

    @PostMapping("/{currentPage}/{pageSize}")
    public Result getPage(@PathVariable("currentPage") int currentPage,
                          @PathVariable("pageSize") int pageSize,
                          @RequestBody User user) {
        return new Result(
                true,
                MessageConstant.QUERY_USER_SUCCESS,
                userService.findPage(currentPage, pageSize, user));
    }
}
